package appController

import (
	"CMETO/models"
	"CMETO/utils"
	"CMETO/utils/jwt"
	"net/http"

	"github.com/gin-gonic/gin"
)

// app部分的接口
type AppLoginController struct{}

// @Summary 用户登录
// @Description 输入账号密码登录
// @Tags APP管理
// @Accept json
// @Produce json
// @Param userInfo body models.LoginParams true "用户信息"
// @Success 200 {object} models.ResultCommon[models.LoginResult] "登录成功"
// @Failure 404 {object} models.ErrorResult "请求失败"
// @Failure 402 {object} models.ErrorResult "用户名或密码错误"
// @Router /app/login [post]
func (l AppLoginController) AppLogin(ctx *gin.Context) {
	var params models.LoginParams
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "登录失败",
			Code:   "400",
			Result: nil,
		})
		return
	}

	params.Password = utils.Sha256(params.Password)
	var user models.User
	models.DB.Where("account=? AND password=?", params.Account, params.Password).First(&user)
	if user.Id == 0 {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "用户名或密码错误",
			Code:   "400",
			Result: nil,
		})
	} else {
		// 查询该用户的角色
		var roleList []models.Role
		models.DB.Model(&models.Role{}).
			Joins("JOIN user_role On roles.id = user_role.role_id").
			Where("user_role.user_id = ? AND roles.is_delete = 0", user.Id).
			Find(&roleList)
		user.Role = roleList
		var userRole []models.UserRole
		models.DB.Table("user_role").Where("user_id = ?", user.Id).Find(&userRole)
		// 签发令牌
		token, _ := jwt.GenerateToken(jwt.UserInfo{
			Id:       user.Id,
			UserName: user.Username,
			Roles:    userRole,
		})
		// 返回结果
		result := models.LoginResult{
			Token:    token,
			UserInfo: user,
		}
		ctx.JSON(http.StatusOK, &models.ResultCommon[models.LoginResult]{
			Msg:    "登录成功",
			Code:   "200",
			Result: result,
		})
	}
}
